<?php
/*
    Might be starting a New Project (no projectid),
    or continuing a New Project (no projectid yet),
    or initiating to clone an existing project (get projectid
        immediately and come back to edit),
    or deleting a project,
    or editing an existing project,
    or completing any of the above and going elsewhere
*/
error_reporting(E_ALL);
$relPath="./../../pinc/";
require_once $relPath."dpinit.php";
include_once($relPath.'dp_main.inc');
include_once($relPath.'theme.inc');
require_once $relPath."lists.php";

// include_once($relPath.'js_newpophelp.inc');

if(! $User->IsLoggedIn()) {
    redirect_to_home();
    exit;
}

if (! $User->IsProjectManager()) {
    die('permission denied');
}

if(IsArg('quitNoSave')) {
    redirect_to_project_manager();
    exit;
}

$projectid        = ArgProjectId();
$saveAndFiles     = IsArg('saveAndFiles');
$saveAndProject   = IsArg('saveAndProject');
$saveAndQuit      = IsArg('saveAndQuit');
$title            = Arg('title');
$author           = Arg('author');
$pm               = Arg('pm', $User->Username());
$ppver            = Arg('ppver');
$language         = Arg('language');    
$other_languages  = Arg('other_languages');    
$genre            = Arg('genre');
$image_source     = Arg('image_source');    
$checkedoutby     = Arg('checkedoutby');    
$image_preparer   = Arg('image_preparer');    
$text_preparer    = Arg('text_preparer');    
$posted           = Arg('posted');
$postednum        = Arg('postednum');
$comments         = Arg('comments');
$clearance        = Arg('clearance');
$difficulty       = Arg('difficulty', "average");
$extra_credits    = Arg('extra_credits');
$asst_pms         = Arg('asst_pms');
$editors          = Arg('editors');
$titlepage        = Arg('titlepage');
$todo             = Arg('todo');

$project = new DpProject($projectid);

$a_errors         = array();

// deleting project
if($todo == "deleteProject") {
    if(! $User->IsSiteManager()) {
        die(_("You are not authorized to delete projects."));
    }
    $project->DeleteAll();
    redirect_to_project_manager();
    exit;
}

if($todo == "clone") {
    $projectid != ""
        or die("No projectid for clone.");
    $project = new DpProject($projectid);
    $project->Exists()
        or die("No project $projectid for clone.");

    $newpid = $project->CloneProject();
    // right back here
    redirect_to_edit_project($newpid);
    exit;
}

// if we have POST data, validate it.
if($saveAndQuit || $saveAndProject || $saveAndFiles) {
    if($todo == "createnew") {
        $project    = new DpProject();
        $projectid  = $project->NewProjectId();
    }

    $projectid != ""
        or die("No project id");

    $project = new DpProject($projectid);
    $project->Exists()
        or die("project $projectid does not exist.");

    $ary = array();

    // 15 elements
    $ary['nameofwork']      = $title;
    $ary['authorsname']     = $author;
    $ary['language']        = $language;
    $ary['other_languages'] = $other_languages;
    $ary['genre']           = $genre;
    $ary['image_source']    = $image_source;
    $ary['checkedoutby']    = $checkedoutby;
    $ary['image_preparer']  = $image_preparer;
    $ary['text_preparer']   = $text_preparer;
    $ary['postednum']       = $postednum;
    $ary['comments']        = $comments;
    $ary['clearance']       = $clearance;
    $ary['titlepage']       = $titlepage;
    $ary['difficulty']      = $difficulty;
    $ary['extra_credits']   = $extra_credits;
    $ary['username']        = $pm;

    $a_errors = $project->UpdateFromArray($ary);

    if($saveAndProject) {
        redirect_to_project($projectid);
    }
    else if($saveAndFiles) {
        redirect_to_filemaster($projectid);
    }
    else {
        redirect_to_project_manager();
    }
    exit;
}

if($todo == "createnew") {
    $projectid == ""
        or die("proj id $projectid submitted with 'create project'.");

    $page_title = _("New Project");
    $project = new DpProtoProject();
    redirect_to_edit_project($project->ProjectId());
    exit;
}

if(isset($project) && $project->Exists()) {
    $title           = $project->Title();
    $author          = $project->Author();
    $language        = $project->LanguageCode();
    $sel_language    = LanguagePicker("other_langs", "", "",
                                        "eOtherLang(event)");
    $other_languages = $project->OtherLanguageCodes();
    $genre           = $project->Genre();
    $difficulty      = $project->Difficulty();
    $pm              = $project->PM();
    $pper            = $project->CheckedOutBy();
    $ppver           = $project->PPVer();
    $imgsource       = $project->ImageSource();
    $imgprep         = $project->ImagePreparer();
    $textprep        = $project->TextPreparer();
    $othercredits    = $project->ExtraCredits();
    $clearance       = $project->Clearance();
    $comments        = $project->Comments();
    $titlepage       = $project->TitlePage();
    $page_title      = $project->Title();
}
else {
    $page_title      = "New project";
    $difficulty      = "average";
    $other_languages = "";
    $pm              = $User->Username();
}
        
 
// $delete_url = url_for_delete_project($projectid);

$js = "
function eOtherLang(e) {
    if(!e) e = window.event;
    var lang = e.target.value;
    if(!lang)
        return;
    var olangs = document.projectform.other_languages;
    olangs.value = (olangs.value ? olangs.value + ' ' + lang : lang);
}

function eDeleteProject() {
    if(window.confirm(\"Are you sure you want to irrecoverably delete this entire project?\")) {
        document.projectform.todo.value = 'deleteProject';
        document.projectform.submit();
        return true;
    }
    else {
        return false;
    }
}";

$args = array("js_data" => $js);
theme($page_title, "header", $args);
echo "<h2 class='center'>$page_title</h2>
<h4>($projectid)</h4>\n";

echo "
<form name='projectform' method='post' 
                        action='' accept-charset='UTF-8'>
<input type='hidden' name='todo' value='edit'>
<table class='editproject'>\n";
if(isset($a_errors) && count($a_errors) > 0) {
    echo "
    <tr><td class='tdleft'>"._("Errors")."</td>
        <td class='tdright'>
        <pre>".implode("\n", $a_errors)."</pre>
    </td>
    </tr>\n";
}

echo "
<tr><td class='tdleft reqd'>"._("Title")."</td>
    <td class='tdright'>
        <input type='text' name='title' id='title' 
            class='textbox' value='".h($title)."'>
    </td>
</tr>

<tr><td class='tdleft reqd'>"._("Author")."</td>
    <td class='tdright'>
        <input type='text' name='author' id='author'
            class='textbox' value='".h($author)."'>
    </td>
</tr>

<tr><td class='tdleft reqd'>"._("Language")."</td>
    <td class='tdright'>\n"
.LanguagePicker("language",  h($language))."
</td></tr>\n";

echo "
<tr><td class='tdleft'>"._("Other language codes")."</td>
    <td class='tdright'>\n"
        .LanguagePicker("other_language", "", "", "eOtherLang(event)")
        ."<input type='text' name='other_languages' size='30' value='"
        .h($other_languages)."' />
    </td>
</tr>\n";

echo "
<tr>
    <td class='tdleft reqd'> "._("Genre")." </td>
    <td class='tdright'>\n"
    .picker($site_genres, "genre", h($genre))."
    </td></tr>\n";

echo "
<tr>
    <td class='tdleft reqd'> "._("Task")." </td>
    <td class='tdright'>\n"
    .picker($site_difficulties, "difficulty",
                            h($difficulty))."
    </td></tr>\n";

echo "
<tr>
".textbox("pm", "Project manager", $pm, true)."
</tr>\n";

echo "
<tr>
".textbox("image_source", "Image source", h($image_source), true)."
</tr>\n";

echo "
<tr>
".textareabox("clearance", "Clearance info", h($clearance), true)."
</tr>\n";

echo "
<tr>
".textbox("checkedoutby", 
                    "Post processor", h($checkedoutby))."
</tr>\n";

echo "
<tr>
".textbox("ppver", "Verifier", h($ppver))."
</tr>\n";

echo "
<tr>
".textbox("image_preparer", "Images prepared by", h($image_preparer))."
</tr>\n";

echo "
<tr>
".textbox("text_preparer", "Text prepared by", h($text_preparer))."
</tr>\n";

echo "
<tr>
".textbox("extra_credits", "Also list in credits", h($extra_credits))."
</tr>\n";

echo "
<tr>
".textbox("titlepage", "Title page".
    ( $titlepage
          ? link_to_display_image(
                    $projectid, $titlepage, " (view)", true)
          : ""
    ),
    $titlepage)
."</tr>\n";

echo "
<tr>
".textareabox("comments", "Project comments", $comments)."\n";

echo "
<tr>
<td colspan='2' class='center'>
    <input type='submit' name='saveAndFiles' id='saveAndFiles'
        value='" . _("Save and manage files")."'>


    <input type='submit' name='saveAndProject' id='saveAndProject'
        value='" . _("Save and view project page")."'>

    <input type='submit' name='saveAndQuit' id='saveAndQuit'
        value='" . _("Save and view PM page")."'>

    <input type='submit' name='quitNoSave' id='quitNoSave'
        value='" . _("Quit Without Saving")."'>\n";

if($User->IsSiteManager() && $projectid != "") {
    echo 
        "\n<input type='button' style='margin: 0 5em'
                    name='deleteProject' id='deleteProject' 
    onclick='eDeleteProject()' value='" . _("Delete Project")."'>";
}

echo "
</td>
</tr>

</table>
</form>\n";

theme_footer();
exit;



// ==============================================================

function textbox($varname, $caption, $curval, $isreqd = false) {
    $caption = $caption;
    $curval = h($curval);
    $reqd    = $isreqd ? " reqd" : "";
    return "
    <td class='tdleft{$reqd}'>"._($caption)."</td>
    <td class='tdright'>
        <input type='text' class='textbox' 
                        name='$varname' id='$varname' value='$curval'>
    </td>\n";
}

function textareabox($varname, $caption, $curval, $isreqd = false) {
    $caption = h($caption);
    $curval = $curval;
    $reqd    = $isreqd ? " reqd" : "";
    return "
    <td class='tdleft{$reqd}'>"._($caption)."</td>
    <td class='tdright'>
    <textarea class='editarea' name='$varname' id='$varname'>\n"
        .$curval
        ."</textarea>
    </td>\n";
}

// ===============================================================


// vim: sw=4 ts=4 expandtab
?>
